<?php
/**
 * This file is part of cdr-bundle.
 * Author: tangzhou
 * Date: 2016/5/4
 * Time: 11:18
 * File: CommonController.php
 */

namespace Icsoc\EsReportBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * 数据报表公共
 * Class CommonController
 * @package Icsoc\EsReportBundle\Controller
 */
class CommonController extends Controller
{
    /**
     * 公共渲染
     * @param String $type
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction($type)
    {
        $data = $this->getTypeData($type);

        return $this->render('IcsocEsReportBundle:Data:index.html.twig', array(
            'type' => $type,
            'data' => $data,
            'date' => $this->get("icsoc_es_report.common")->getDate(),
        ));
    }

    /**
     * 呼叫中心整体话务报表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function systemAction()
    {
        return $this->forward("IcsocEsReportBundle:Common:index", array('type'=>'system'));
    }

    /**
     * 技能组报表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function queueAction()
    {
        return $this->forward("IcsocEsReportBundle:Common:index", array('type'=>'queue'));
    }

    /**
     * 坐席工作表现报表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function agentAction()
    {
        return $this->forward("IcsocEsReportBundle:Common:index", array('type'=>'agent'));
    }

    /**
     * 业务组报表
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function groupAction()
    {
        return $this->forward("IcsocEsReportBundle:Common:index", array('type'=>'group'));
    }

    /**
     * 展示列表
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listAction(Request $request)
    {
        $data = $request->get('data', '');
        $data = html_entity_decode(urldecode($data));
        $data = json_decode($data, true);
        $param['report_type'] = empty($data['report_type']) ? '' : $data['report_type'];
        $param['start_date'] = empty($data['start_date']) ? '' : $data['start_date'];
        $param['end_date'] = empty($data['end_date']) ? '' : $data['end_date'];
        $param['data_id'] = empty($data['data_id']) ? '' : $data['data_id'];
        $param['type'] = empty($data['type']) ? '' : $data['type'];
        $rst = $this->get('icsoc_es_report.model.report')->getTitleReport(
            array('report_name'=>$param['type'], 'report_type'=>$param['report_type'])
        );
        $title = array();
        if (isset($rst['code']) && $rst['code'] == 200) {
            $title = $rst['data'];
        }

        $item['title'] = $title;
        $item['caption'] = ucfirst($param['type']).' Caption 【%start_date% ~ %end_date%】';
        $item['start_date'] = empty($param['start_date']) ? '' : $param['start_date'];
        $item['end_date'] = empty($param['end_date']) ? '' : $param['end_date'];
        $item['report_type'] = $this->get("translator")->trans($param['report_type']);

        return $this->render('IcsocEsReportBundle:Data:list.html.twig', array(
            'item'=>$item,
            'param'=>json_encode($param),
        ));
    }

    /**
     * 获取列表数据
     * @param Request $request
     * @return JsonResponse
     */
    public function dataAction(Request $request)
    {
        $data = $request->get('param', '');
        $data = html_entity_decode(urldecode($data));
        $data = json_decode($data, true);
        $startDate = empty($data['start_date']) ? '' : $data['start_date'];
        $endDate = empty($data['end_date']) ? '' : $data['end_date'];
        $dataId = empty($data['data_id']) ? '' : $data['data_id'];
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'Desc');
        $sidx = $request->get('sidx', '1');
        $sidx = $this->getSortField($sidx, $data['report_type']);
        $export = $request->get('export', '');
        $title = $request->get('title', '');

        /** @var  $param (数据参数) */
        $param = array(
            'export' => $export,
            'pagination' => array(
                'rows' => $rows,
                'page' => $page,
            ),
            'sort' => array(
                'order' => $sord,
                'field' => $sidx,
            ),
            'filter' => array(
                'start_date' => $startDate,
                'end_date' => $endDate,
                'data_id' => $dataId,
            ),
        );
        $param = array(
            'vcc_code' => $this->getUser()->getVccCode(),
            'info' => json_encode($param),
            'rep_type' => $data['report_type'],
            'type' => $data['type'],
        );
        $result = $this->get('icsoc_es_report.model.report')->getData($param);
        $translator = $this->get('translator');
        if ($result['code'] == 200) {
            $result = array(
                'total' => $result['total'],
                'page' => $result['page'],
                'records' => $result['records'],
                'rows' => $result['rows'],
                'userdata' => $result['footer'],
            );
        } else {
            $result = array(
                'total' => 0,
                'page' => 1,
                'records' => 0,
                'rows' => array(),
                'code' => $result['code'],
                'message' => $result['message'],
            );
        }

        /** 导出功能 */
        if (!empty($export)) {
            $gridData[] = $result['userdata'];
            $title = json_decode($title, true);
            $titleItem = array();
            foreach ($title as $key => $v) {
                $titleItem[$v['field']] = $v['text'];
            }
            $text = sprintf('%s Caption', ucfirst($data['type']));
            $href = sprintf('icsoc_es_report_%s_home', $data['type']);
            switch ($export) {
                case 'csv':
                    return $this->get('icsoc_es_report.common')->exportCsv($gridData, json_encode($titleItem), array(
                        'text' => $translator->trans($text),
                        'href' => $this->generateUrl($href),
                    ));
                case 'excel':
                    return $this->get('icsoc_es_report.common')->exportExcel($gridData, json_encode($titleItem), array(
                        'text' => $translator->trans($text),
                        'href' => $this->generateUrl($href),
                    ));
                default:
                    exit;
            }
        }

        return new JsonResponse($result);
    }

    /**
     * 根据type获取Data
     * @param $type
     * @return array
     */
    private function getTypeData($type)
    {
        $data = array('is_show'=>1);
        switch ($type) {
            case 'system':
                $data['is_show'] = 0;
                break;
            case 'queue':
                $data['text'] = $this->get("translator")->trans('Queues');
                $data['please'] = $this->get("translator")->trans('Please Select Queues');
                $row = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($this->getUser()->getVccId(), true, true);
                $data['data'] = $row;
                break;
            case 'group':
                $em = $this->getDoctrine()->getManager();
                $vccId = $this->getUser()->getVccId();
                $row = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
                $data['text'] = $this->get("translator")->trans('Groups');
                $data['please'] = $this->get("translator")->trans('Please Select Groups');
                $data['data'] = $row;
                break;
            case 'agent':
                $row = $this->get('icsoc_data.model.agent')->getAgentNameKeyedByIdArray($this->getUser()->getVccId(), true);
                $data['text'] = $this->get("translator")->trans('Agents');
                $data['please'] = $this->get("translator")->trans('Please Select Agents');
                $data['data'] = $row;
                break;
        }

        return $data;
    }

    /**
     * 获取日期的排序字段
     * @param $sidx
     * @param $type
     * @return array|string
     */
    private function getSortField($sidx, $type)
    {
        if ($sidx == 'date') {
            switch ($type) {
                case 'month':
                    $sidx = 'current_date';
                    break;
                case 'day':
                    $sidx = 'current_date';
                    break;
                case 'hour':
                    $sidx = array('current_date', 'time_stamp');
                    break;
                case 'halfhour':
                    $sidx = array('current_date', 'time_stamp');
                    break;
            }
        }

        return $sidx;
    }
}
